Integrating Sessions in your Program
Integrate and manage sessions in your Solana Programs
This guide demonstrates how to integrate Session Keys into your Solana Anchor programs, using a simple counter program as an example.
Installation
First, add the session-keys crate to your Cargo.toml:
Or use the cargo command:
Usage
- Importing session-keys:
This line imports the necessary components from the session-keys crate.
- Deriving the Session trait:
The Session
trait is derived on the Increment
struct, enabling session functionality.
- Defining the session token account:
This defines an optional SessionToken
account, specifying the signer and authority for the session.
- session_token.authority: account which created the session token
- counter.authority.key(): account which created the counter The authority condition checks if the session token is created by the same user as the counter.
- Using the
session_auth_or
macro:
This macro is applied to the increment
function.
It checks for a valid session token, or if not present, verifies that the signer is the counter’s authority.
Full Example
Here’s a complete example of a counter program using session keys. Each user gets his own counter account, so we can show how authentication is done with session keys.
Tests
Here’s an example of how to test the counter program with session keys:
This test suite demonstrates initializing the counter, incrementing it without a session, creating a session token, and then incrementing with the session token. The last test is important, as it ensures that only the owner of the counter can increment it.
Testing locally
To test it locally with solana-test-validator
, you need to start it with the session keys program and account.
- Make sure your Solana CLI points to DEVNET:
- Dump Session Keys program to local file:
- Start solana-test-validator with session keys program and account:
-r
- reset the ledger to genesis-ud
- URL for Solana’s JSON RPC or moniker (-ud = DEVNET)--clone
- Copy an account from the cluster--bpf-program
- add a SBF program to the genesis configuration
Was this page helpful?